import random
import string

from django.contrib.auth.models import Group
from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_201_CREATED
from rest_framework.viewsets import ModelViewSet

from celery_tasks.email.tasks import send_mail_task
from utils.permission import TeacherPermission
from .serializers import *
from rest_framework.permissions import IsAuthenticated


class ClassesViewSet(ModelViewSet):
    queryset = classes.objects.filter(is_delete=False)
    serializer_class = ClassesSerializer
    permission_classes = [TeacherPermission]

    def get_serializer(self, *args, **kwargs):
        if self.action == 'students':
            return CreateUserSerializer(*args, **kwargs)
        return self.serializer_class(*args, **kwargs)

    @action(methods=['post'], detail=True)
    def students(self, request, pk):
        # 获取班级
        try:
            classes = self.get_queryset().get(id=pk)
        except classes.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        # 得到前端传入的数据
        username = request.data['username']
        email = request.data['email']
        first_name = request.data['first_name']

        member = classes.member.filter(username=username)
        if member:
            # 如果在，则返回，并提示已存在
            return Response({'msg': '该成员已经加入该班级'})
        # 如果不在， 则判断用户是否存在，即判断是否是新学员
        user = User.objects.filter(username=username)
        if user:
            user = user.first()
            classes.member.add(user)
            # 如果存在， 将该用户添加到班级并返回
            return Response(self.get_serializer(user).data)

        # 如果不存在， 则创建用户
        # 使用序列化器进行反序列化，校验传入捡来的数据
        user_serializer = self.get_serializer(data=request.data)
        user_serializer.is_valid(raise_exception=True)
        user = User(username=username, email=email, first_name=first_name)

        # 判断用户是否已经在该班级,查询班级的所有成员，以用户作为条件

        # 生成初始密码
        source = string.ascii_letters + string.digits
        password = ''.join(random.sample(source, 6))
        user.set_password(password)  # 给用户设置密码，会进行加密，存储密文
        user.save()

        # 发送邮件
        # print(email, username, password, classes.name)
        # 设置为学生身份
        group = Group.objects.get(id=2)
        group.user_set.add(user)

        # 添加班级
        classes.member.add(user)

        # 生产邮件发送异步任务
        send_mail_task.delay(email, username, password, classes.name)

        # 返回
        return Response(user_serializer.data, status=HTTP_201_CREATED)
